package com.dark.aop.exception;

import com.dark.base.FlowerFallingErrorCodeEnmu;
import com.dark.base.FlowerFallingException;
import com.dark.base.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 *
 * @author chengluchao
 * @date 2024-04-16 20:21
 */
@Slf4j
@Order(0)
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 自定义异常处理器
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = FlowerFallingException.class)
    @ResponseBody
    public Result flowerFallingExceptionHandler(FlowerFallingException exception) {
        log.error("业务异常 exception=", exception);
        Result result = new Result(exception.getCode(), exception.getMessage());
        return result;
    }

    /**
     * 未知异常处理器
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception exception) {
        log.error("系统未知异常 exception=", exception);
        Result result = new Result();
        result.setCode(FlowerFallingErrorCodeEnmu.ERROR.getCode());
        result.setMessage(FlowerFallingErrorCodeEnmu.ERROR.getMessage());
        return result;
    }

    /**
     * 参数校验异常处理
     *
     * @param exception
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) {
        String message = exception.getBindingResult().getFieldError().getDefaultMessage();
        log.error("参数校验不通过 exception={}", message);
        Result result = new Result(FlowerFallingErrorCodeEnmu.METHOD_ARGUMENT_NOT_VALID_ERROR.getCode(), message);
        return result;
    }

    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Result bindExceptionHandler(BindException exception) {
        String message = exception.getBindingResult().getFieldError().getDefaultMessage();
        log.warn("参数校验失败：{}", message);
        Result result = new Result(FlowerFallingErrorCodeEnmu.METHOD_ARGUMENT_NOT_VALID_ERROR.getCode(), message);
        return result;
    }

}